﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ufida.u9.ait.openapi.utils;
using UFIDA.U9.Base;
using UFIDA.U9.Base.Currency;
using UFIDA.U9.Base.Doc;
using UFIDA.U9.Base.Organization;
using UFIDA.U9.CBO.HR.Department;
using UFIDA.U9.CBO.HR.Operator;
using UFIDA.U9.CBO.SCM.Enums;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.CBO.SCM.ProjectTask;
using UFIDA.U9.CBO.SCM.Warehouse;
using UFIDA.U9.ISV.PRSV;
using UFIDA.U9.PR.PurchaseRequest;
using UFIDA.U9.SM.DealerSO;
using UFSoft.UBF.Business;

namespace ufida.u9.ait.openapi
{
    internal class PRBase
    {
        public static PR DeleteDoc(PR doc)
        {
            if(doc==null||doc.ID<=0) return null;

            DeletePRSVForOtherSys sv = new DeletePRSVForOtherSys();
            sv.PRConditionDTOList = new List<PRConditionDTO>()
            {
                new PRConditionDTO()
                {
                    PRID=doc.ID
                }
            };

            return doc;
        }
        public static PR CommitDoc(PR doc)
        {
            //清除缓存,否则提交会报错
            U9Utils.ClearCache();
            doc = doc.Key.GetEntity();
            //提交处理
            using (ISession session = Session.Open())
            {
                foreach (PRLine line in doc.PRLineList)
                {
                    line.Status = PRStatusEnum.Approving;
                    line.ActivityType = ActivityTypeEnum.SrvUpdate;
                }
                doc.Status = PRStatusEnum.Approving;

                session.Commit();
            }

            return doc;
        }
        public static PR ApproveDoc(PR doc)
        {
            //刷新实体版本
            doc = doc.Key.GetEntity();
            //审核处理过程
            using (ISession session = Session.Open())
            {
                foreach (PRLine line in doc.PRLineList)
                {
                    line.Status = PRStatusEnum.Approved;
                    line.ActivityType = ActivityTypeEnum.SrvUpdate;
                }
                doc.ApprovedOn = DateTime.Now;
                doc.ApprovedBy = Context.LoginUser;
                doc.Status = PRStatusEnum.Approved;
                doc.CancelApprovedBy = null;
                //be.CancelApprovedOn = DateTime.Now;
                session.Commit();
            }
            return doc;
        }
        /// <summary>
        /// 创建请购单
        /// </summary>
        /// <param name="dto">传入DTO</param>
        /// <returns>请购单实体</returns>
        public static PR CreatePR(PRAITDTOData dto)
        {
            PR doc;
            using (ISession session = Session.Open())
            {
                //创建表头
                doc = CreateHead(dto);
                //创建表体
                CreateLine(doc, dto);

                session.Commit();
            }
            return doc;
        }

        private static void CreateLine(PR doc, PRAITDTOData dto)
        {
            foreach (var linedto in dto.PRLineList)
            {
                PRLine line = PRLine.Create(doc);
                LineDefault(dto,linedto, line);
                LineQty(linedto, line);
            }
        }

        private static void LineDefault(PRAITDTOData dto, PRLineAITDTOData linedto, PRLine line)
        {
            PR doc = line.PR;
            //行号
            if (linedto.DocLineNo == 0)
            {
                line.DocLineNo = doc.PRLineList.Count * 10;
            }
            else
            {
                line.DocLineNo = linedto.DocLineNo;
            }

            line.SrcDocType = doc.SourceType;
            //line.BizType = UFIDA.U9.Base.Doc.BusinessTypeEnum.PM055;
            line.BizType = BusinessTypeEnum.Empty;
            //组织
            line.ShipperOrg = doc.Org;
            line.RegOrg = doc.Org;
            line.RcvOrg = doc.Org;
            line.CurrentOrg = doc.Org;
            line.BudgetLeagcyOrg = doc.Org;
            line.AccountOrg = doc.Org;

            //料品
            line.ItemInfo = new ItemInfo();
            ItemMaster itemMaster = EntityUtils.GetEntityByCode<ItemMaster>(linedto.ItemInfo?.ItemCode);
            line.ItemInfo.ItemID = itemMaster;
            line.ItemInfo.ItemCode = itemMaster.Code;
            line.ItemInfo.ItemName = itemMaster.Name;

            //要求交货日期
            if (!string.IsNullOrEmpty(linedto.RequiredDeliveryDate))
            {
                line.RequiredDeliveryDate = DateTime.Parse(linedto.RequiredDeliveryDate);
            }
            else
            {
                line.RequiredDeliveryDate = doc.BusinessDate;
            }

            //应下单日期
            line.ToOrderDate = line.RequiredDeliveryDate;
            //计划到货日期
            line.PlanDueDate = line.RequiredDeliveryDate;
            //提交日期
            //line.DeliveryDate = DateTime.Now;

            //扩展字段处理
            if (linedto.DescFlexSegments != null)
            {
                line.DescFlexSegments = new UFIDA.U9.Base.FlexField.DescFlexField.DescFlexSegments();
                DTOUtils.DTOPropCopy(linedto.DescFlexSegments, line.DescFlexSegments);
            }

            //其他字段
            line.PurPerson = EntityUtils.GetEntityByCode<Operators>(linedto.PurPerson);
            line.PurDepartment = EntityUtils.GetEntityByCode<Department>(linedto.PurDepartment);
            line.ReqEmployee = EntityUtils.GetEntityByCode<Operators>(linedto.ReqEmployee);
            line.ReqDept = EntityUtils.GetEntityByCode<Department>(linedto.ReqDept);
            line.PriceUOMEditable = true;
            line.IsSupplierConfirm = true;
            line.ISSeiBanChange = true;
            line.IsMRPDemand = true;
            line.Memo = linedto.Memo;
            line.BizType = BusinessTypeEnum.GetFromValue(dto.BizType);//业务类型 -1=标准请购 326=委外请购
            line.Project = EntityUtils.GetEntityByCode<Project>(linedto.Project);//项目
            line.Warehouse = EntityUtils.GetEntityByCode<Warehouse>(linedto.Warehouse);//存储地点
        }

        /// <summary>
        /// 计量单位/数量/转换率
        /// </summary>
        /// <param name="linedto"></param>
        /// <param name="line"></param>
        private static void LineQty(PRLineAITDTOData linedto, PRLine line)
        {
            ItemMaster itemMaster = line.ItemInfo.ItemID;
            //计量单位
            line.StoreUOM = itemMaster.InventorySecondUOM;
            line.StoreBaseUOM = itemMaster.InventorySecondUOM.BaseUOM;
            line.WeightUOM = itemMaster.WeightUom;
            line.TradeUOM = itemMaster.PurchaseUOM;
            line.TradeBaseUOM = itemMaster.PurchaseUOM.BaseUOM;
            line.ReqUOM = itemMaster.PurchaseUOM;
            line.ReqBaseUOM = itemMaster.PurchaseUOM.BaseUOM;
            line.PriceUOM = itemMaster.PriceUOM;
            line.PriceBaseUOM = itemMaster.PriceUOM.BaseUOM;
            line.ItemBulkUOM = itemMaster.BulkUom;

            //数量
            if (linedto.ReqQtyTU == 0) throw new Exception("ReqQtyTU 为空");
            line.ReqQtyTU = linedto.ReqQtyTU;
            line.ReqQtyReqUOM = linedto.ReqQtyTU * U9Utils.GetUom2Rate(line.TradeUOM, line.ReqUOM, itemMaster);
            if (linedto.ReqQtyTU > 0)
            {
                line.ReqQtyPU = linedto.ReqQtyPU;//计价单位
            }
            else
            {
                line.ReqQtyPU = linedto.ReqQtyTU * U9Utils.GetUom2Rate(line.TradeUOM, line.PriceUOM, itemMaster);
            }
            line.ReqQtySU = linedto.ReqQtyTU * U9Utils.GetUom2Rate(line.TradeUOM, line.StoreUOM, itemMaster);
            line.ApprovedQtyTU = line.ReqQtyTU;
            line.ApprovedQtyReqUOM = line.ReqQtyReqUOM;
            line.ApprovedQtyPU = line.ReqQtyPU;
            line.ApprovedQtySU = line.ReqQtySU;

            //转换率
            line.SBUToTBURate = U9Utils.GetUom2Rate(line.StoreBaseUOM, line.TradeBaseUOM, itemMaster);
            line.TUToTBURate = line.TradeUOM.RatioToBase;
            line.TBUToPBURate = line.ReqQtyPU / line.ReqQtyTU;//交易-计价
            line.ReqUOMToReqBaseUOMRate = line.ReqUOM.RatioToBase;
            line.ReqBUOMToTBURate = U9Utils.GetUom2Rate(line.ReqBaseUOM, line.TradeBaseUOM, itemMaster);
            line.PUToPBURate = line.PriceUOM.RatioToBase;
        }

        private static PR CreateHead(PRAITDTOData dto)
        {
            PR doc = PR.Create();
            //doc.DocNo = dto.DocNo;//单号
            if (string.IsNullOrEmpty(dto.BusinessDate))
                throw new Exception("单据日期[BusinessDate]为空");
            doc.BusinessDate = DateTime.Parse(dto.BusinessDate);//单据日期
            if (dto.PRDocType == null)
                throw new Exception("单据类型[PRDocType]为空");
            doc.PRDocType = EntityUtils.GetEntityByCode<PRDocType>(dto.PRDocType.Code);

            //组织
            doc.Org = Context.LoginOrg;
            doc.LegacyOrg = doc.Org;
            doc.AccountOrg = doc.Org;

            //扩展字段
            if (dto.DescFlexField != null)
            {
                doc.DescFlexField = new UFIDA.U9.Base.FlexField.DescFlexField.DescFlexSegments();
                DTOUtils.DTOPropCopy(dto.DescFlexField, doc.DescFlexField);
            }
            //其他
            if (dto.FC == null)
            {
                doc.FC = EntityUtils.GetEntityByCode<Currency>("C001");
            }
            else
            {
                doc.FC = EntityUtils.GetEntityByCode<Currency>(dto.FC.Code);
            }
            doc.ETEditable = true;
            doc.SourceType = SrcDocTypeEnum.Manual;//来源类型=手工
            doc.IsControlQtyByPR = true;//按请购控制数量=true
            doc.IsOverPurchase = true;
            doc.ACFCRate = 1;
            doc.ACEditable = true;
            doc.ReqDepartment = EntityUtils.GetEntityByCode<Department>(dto.ReqDepartment);//需求部门
            doc.ReqEmployee = EntityUtils.GetEntityByCode<Operators>(dto.ReqEmployee);//需求人员
            doc.Memo = dto.Memo;

            return doc;
        }
    }
}
